//
//  ClientAdressViewController.swift
//  SlaughterClient
//
//  Created by zwb on 2018/5/31.
//  Copyright © 2018年 zwb. All rights reserved.
//

import UIKit
enum ZyaCAddrType:String {
    case recive = "0",send = "1"  // 收货地址 发货地址
}

class ZyaClientAddressController: UITableViewController {
    
    var addressArr = [ZyaClientAddress]()
    var typeX:ZyaCAddrType!
    init(type:ZyaCAddrType){
        super.init(nibName: nil, bundle: nil)
        self.typeX = type
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
         tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 70
        tableView.separatorStyle = .none
        tableView.backgroundColor = Theme.tableViewColor
        view.backgroundColor = Theme.backgroudColor
        tableView.register(ZyaClientAddressCell.nib, forCellReuseIdentifier: ZyaClientAddressCell.identifier)
     
        tableView.mj_header = KSRefreshHeader {
            self.fetchData()
        }
        tableView.mj_header?.beginRefreshing()
    }
    
    func fetchData() {
        KSNetwork.shared.doRequest(API.queryClientAddress(k_addr_type: self.typeX.rawValue)) { (data: BaseResult<ZyaClientAddress>) in
          
                if let infos = data.infoArrCombine {
                    self.addressArr = infos
                    self.tableView.mj_header?.endRefreshing()
                    self.tableView.reloadData()
                    
                    //赋值全局变量，物流信息那边要用
                    if self.typeX.rawValue == "1" {
                        zyasendAddrArr = infos
                    }
                    // 收货地址饲料订单那边用
                    if self.typeX.rawValue == "0" {
                        zyareceiveAddrArr = infos
                    }
                }
                
             
            
        }
    }
 
}

extension ZyaClientAddressController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return addressArr.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ZyaClientAddressCell.identifier, for: indexPath) as! ZyaClientAddressCell
        cell.model = addressArr[indexPath.row]
        cell.updateAddress = { [unowned self] in
            let vc = ZyaAddressFormVC(type: self.typeX)
            vc.refreshClosure = {
                self.tableView.mj_header?.beginRefreshing()
            }
            vc.title = "修改地址"
            vc.model = self.addressArr[indexPath.row]
             vc.currentMark = self.addressArr[indexPath.row].currMark ?? 0
            vc.idKey = self.addressArr[indexPath.row].idKey ?? ""
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        cell.deleteAddress = { [unowned self] in
            let alert = UIAlertController(title: "确认删除该地址", message: "", preferredStyle: .alert)
            let delete = UIAlertAction(title: "确定", style: .default) { (_) in

                guard let id = self.addressArr[indexPath.row].idKey else {
                    return
                }
                
                KSNetwork.shared.doRequest(API.deleteClientAddress(idkey: id), successHandle: { (data: BaseResult<OperateResult>) in
                    KSToast(data.message, duration: 1.0, position: .center)
                    if data.message == "删除成功" {
                        self.tableView.beginUpdates()
                        self.addressArr.remove(at: indexPath.row)
                        self.tableView.deleteRows(at: [indexPath], with: .automatic)
                        self.tableView.endUpdates()
                        self.tableView.reloadData()
                    }
                })
            }
            
            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(delete)
            alert.addAction(cancel)
            self.present(alert, animated: true, completion: nil)
        }
        
        cell.selectAddress = { [unowned self] in
            let alert = UIAlertController(title: "确认设置为默认地址", message: "", preferredStyle: .alert)
            let delete = UIAlertAction(title: "确定", style: .default) { (_) in

                self.addressArr[indexPath.row].currMark = 1
                
                guard let data = self.addressArr[indexPath.row].toJSONString() else {
                    return
                }
                
                guard let id = self.addressArr[indexPath.row].idKey else {
                    return
                }
                
                KSNetwork.shared.doRequest(API.addClientAddress(data: data, idKey: id)) { (data: BaseResult<OperateResult>) in
                    if data.message.unwrap.contains("成功") {
                        self.fetchData()
                    }
                }
            }
            
            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(delete)
            alert.addAction(cancel)
            self.present(alert, animated: true, completion: nil)
        }
        return cell
    }
}
